/**
 * 
 * Copyright (C) 2011 Cody Stoutenburg . All rights reserved.
 *
 *       This program is free software; you can redistribute it and/or
 *       modify it under the terms of the GNU Lesser General Public License
 *       as published by the Free Software Foundation; either version 2.1
 *       of the License, or (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU Lesser General Public License for more details.
 *
 *       You should have received a copy of the GNU Lesser General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 * 
 */
package client.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Set;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;

import client.ChatClient;

/**
 * @author Cody Stoutenburg
 * 
 */
public class PanelContactList extends JPanel {

	private static final long serialVersionUID = 9108811179046906167L;

	private final Set<JCheckBox> allContact;
	private final JButton selectAll;
	private final JButton deselectAll;
	private final ChatClient chat;

	public PanelContactList(ChatClient chat) {
		super();
		allContact = new HashSet<JCheckBox>();
		this.chat = chat;
		selectAll = new JButton("selectionner tous");
		deselectAll = new JButton("deselectionner tous");

		selectAll.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				applyToAllContact(true);
			}
		});

		deselectAll.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				applyToAllContact(false);
			}
		});

		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

		updateComponent();
	}

	public void applyToAllContact(boolean isSelected) {
		for (JCheckBox check : allContact) {
			check.setSelected(isSelected);
		}
	}

	public void updateClient() {
		allContact.clear();
		for (String name : chat.getAllConnectedPeople()) {
			if (!name.equals(chat.getPseudo())) {
				allContact.add(new JCheckBox(name));
			}
		}
		updateComponent();
	}

	private void updateComponent() {
		this.removeAll();
		for (JCheckBox client : allContact) {
			this.add(client);
		}
		this.add(selectAll);
		this.add(deselectAll);
		this.revalidate();
	}

	public Set<String> getAllContactSelected() {
		Set<String> allSelected = new HashSet<String>();
		for (JCheckBox checked : allContact) {
			if (checked.isSelected()) {
				allSelected.add(checked.getText());
			}
		}

		return allSelected;
	}
}
